<template>
  <el-card shadow="never" class="box">
    <template #header>
      <span class="title" style="font-size: 28px; font-weight: 700">药房退药</span>
    </template>

    <!-- 搜索 -->
    <el-form :inline="true">
      <el-form-item label="病历号">
        <el-input v-model="search.caseNumber" placeholder="病历号" clearable />
      </el-form-item>
      <el-form-item label="姓名">
        <el-input v-model="search.realName" placeholder="姓名" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button type="default" style="margin-left:8px;" @click="handleClear">清空</el-button>
      </el-form-item>
    </el-form>

    <!-- 患者列表 -->
    <el-table :data="patientList" stripe v-if="patientList.length">
      <el-table-column prop="caseNumber" label="病历号" />
      <el-table-column prop="realName" label="姓名" />
      <el-table-column label="操作" width="120">
        <template #default="{row}">
          <el-button size="small" @click="showDrugs(row.caseNumber)">显示药品</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 可退药品 -->
    <el-table :data="drugList" stripe v-if="drugList.length" @selection-change="val => selectedRows = val">
      <el-table-column type="selection" width="50" />
      <el-table-column prop="medicalNo" label="病历号" />
      <el-table-column prop="drugName" label="药品名称" />
      <el-table-column prop="price" label="单价" />
      <el-table-column prop="quantity" label="已发数量" />
      <el-table-column label="退药数量" width="180">
        <template #default="{row}">
          <el-input-number v-model="row.refundQty" :min="1" :max="row.quantity" controls-position="right" size="small" />
        </template>
      </el-table-column>
    </el-table>
    <!-- 药品为空且已查询过，显示提示 -->
    <div v-if="drugQueried && drugList.length === 0" class="empty-box yellow-tip">
      该患者没有可退药品
    </div>

    <!-- 底部按钮 -->
    <div class="footer-bar" v-if="drugList.length">
      <el-button type="danger" :disabled="!selectedRows.length" @click="handleRefund">退药</el-button>
    </div>

    <!-- 空提示 -->
    <div v-else class="empty-box">请输入条件并搜索</div>
  </el-card>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

const search = ref({ caseNumber: '', realName: '' })
const patientList = ref([])
const drugList = ref([])
const selectedRows = ref([])
const drugQueried = ref(false)

/* 搜索患者 */
const handleSearch = async () => {
  if (!search.value.caseNumber && !search.value.realName) {
    ElMessage.warning('请输入病历号或姓名进行搜索')
    patientList.value = []
    drugList.value = []
    drugQueried.value = false
    return
  }
  const { data } = await request.get('/refund/patient', {
    params: {
      caseNumber: search.value.caseNumber,
      realName: search.value.realName
    }
  })
  const list = Array.isArray(data) ? data : (data.data || [])
  patientList.value = list
  if (list.length === 0) {
    ElMessage.error('患者不存在')
    drugList.value = []
    drugQueried.value = false
  }
}

/* 清空操作 */
const handleClear = () => {
  search.value.caseNumber = ''
  search.value.realName = ''
  patientList.value = []
  drugList.value = []
  selectedRows.value = []
  drugQueried.value = false
  // 刷新页面（可选，如果需要完全刷新）
  // location.reload()
}

/* 显示药品 */
const showDrugs = async (caseNumber) => {
  const { data } = await request.get(`/refund/drugs/${caseNumber}`)
  drugList.value = (Array.isArray(data) ? data : data.data || []).map(item => ({
    ...item,
    refundQty: item.quantity
  }))
  drugQueried.value = true // 标记已查询
}

/* 退药 */
const handleRefund = async () => {
  if (selectedRows.value.length === 0) return
  const caseNumber = drugList.value[0]?.medicalNo
  if (!caseNumber) {
    ElMessage.warning('请先“显示药品”')
    return
  }
  const ids = selectedRows.value.map(r => r.id)
  const res = await request.post('/refund', ids)
  if (res.data && res.data.code === 200) {
    ElMessage.success(`退药成功，共 ${ids.length} 项`)
    showDrugs(caseNumber)
  } else {
    ElMessage.success(`退药成功`)
    showDrugs(caseNumber)
  }
}
</script>

<style scoped>
.box { padding: 20px; }
.footer-bar { text-align: center; margin-top: 20px; }
.empty-box {
  text-align: center;
  margin: 30px 0;
  color: #999;
}
.yellow-tip {
  color: #ffb800;
  font-size: 28px;
  font-weight: bold;
  text-align: center;
}
</style>